#import "EditSlideshow.h"

#import "Controller.h"
#import "SlideshowModel.h"
#import "Utility.h"


#define PREF_EDIT_SLIDESHOW_FOLDER_TABLE	@"EditSlideshow.folderTable"
#define PREF_EDIT_SLIDESHOW_IGNORE_TABLE	@"EditSlideshow.ignoreTable"


@implementation EditSlideshow

//--------------------------------------------------------------------------------------------------
- (id) initEmpty
{
	self = [super init];
	if (nil != self)
	{
		ssModel = [[SlideshowModel alloc] initEmpty];
	}

	return self;
}

//--------------------------------------------------------------------------------------------------
- (id) initWithModel:(SlideshowModel*) model
{
	self = [super init];
	if (nil != self)
	{
		ssModel = [[SlideshowModel alloc] initWithModel: model];
		[ssModel retain];
	}

	return self;
}

//--------------------------------------------------------------------------------------------------
- (void) dealloc
{
	[ssModel release];
	[lastFolderChosen release];

	[super dealloc];
}

//--------------------------------------------------------------------------------------------------
- (void) awakeFromNib
{
	if (YES == [ssModel autoShow])
	{
		[autoSlides setState: 1];
		[durationTime setTitleWithMnemonic: [NSString stringWithFormat: @"%u", [ssModel duration]]];
//    IBOutlet NSComboBox		*durationUnits;
	}
	else
	{
		[autoSlides setState: 0];
		[durationTime setEnabled: NO];
		[durationUnits setEnabled: NO];
	}

	if (nil != [ssModel name])
	{
		[nameText setTitleWithMnemonic: [ssModel name]];
	}

//    IBOutlet NSButton		*okButton;
	switch ([ssModel sortBy])
	{
		case SS_SORT_DATE:
			[order selectCellWithTag: 2];
			break;

		case SS_SORT_NAME:
			[order selectCellWithTag: 3];
			break;

		case SS_SORT_NONE:
		default:
			[order selectCellWithTag: 1];
			break;
	}

	[folderList setColumnAutoresizingStyle: NSTableViewFirstColumnOnlyAutoresizingStyle];
	[ignoreList setColumnAutoresizingStyle: NSTableViewFirstColumnOnlyAutoresizingStyle];

	[folderList setDataSource: self];
	[folderList setDelegate: self];
	[ignoreList setDataSource: self];
	[ignoreList setDelegate: self];

	[folderList reloadData];
	[ignoreList reloadData];
}

//--------------------------------------------------------------------------------------------------
- (IBAction)addFolder:(id)sender
{
	NSOpenPanel *open = [NSOpenPanel openPanel];

	[open setAllowsMultipleSelection: YES];
	[open setCanChooseDirectories: YES];
	[open setCanCreateDirectories: YES];
	[open setCanChooseFiles: NO];
	[open setPrompt: NSLocalizedString(@"Choose folder", @"Choose folder")];
	[open setTitle: NSLocalizedString(@"Choose folder", @"Choose folder")];

	NSString *dir = lastFolderChosen;
	if (nil == dir)
	{
		dir = GetPicturesFolder();
	}

	int retCode = [open runModalForDirectory: dir  file: nil  types: nil];
	if (NSOKButton == retCode)
	{
		lastFolderChosen = [[open filename] stringByDeletingLastPathComponent];
		[lastFolderChosen retain];

		NSEnumerator *iter = [[open filenames] objectEnumerator];
		id name;
		while (name = [iter nextObject])
		{
			SSPathData *ss = [[SSPathData alloc] initWithName: name];
			[[ssModel folderList] addObject: ss];
			[ss release];
		}

		[folderList reloadData];
	}
}

//--------------------------------------------------------------------------------------------------
- (IBAction)removeFolder:(id)sender
{
	NSIndexSet *selItems = [folderList selectedRowIndexes];
	if ([selItems count] != 1)
	{
		return;
	}

	int row = [selItems firstIndex];
	[[ssModel folderList] removeObjectAtIndex: row];
	[folderList reloadData];

	// Try to ensure something is selected
	if (-1 == [folderList selectedRow] && [[ssModel folderList] count] > 0)
	{
		while (row >= [[ssModel folderList] count] && row > 0)
		{
			--row;
		}
		[folderList selectRow: row  byExtendingSelection: NO];
	}
}

//--------------------------------------------------------------------------------------------------
- (IBAction)editFolder:(id)sender
{
}

//--------------------------------------------------------------------------------------------------
- (IBAction)autoChangeSlidesClick:(id)sender
{
	if (1 == [autoSlides state])
	{
		[durationTime setEnabled: YES];
		[durationUnits setEnabled: YES];
	}
	else
	{
		[durationTime setEnabled: NO];
		[durationUnits setEnabled: NO];
	}
}

//--------------------------------------------------------------------------------------------------
- (IBAction)addIgnore:(id)sender
{
	SSPathData *ss = [[SSPathData alloc] initWithName: @""];
	[[ssModel ignoreList] addObject: ss];
	[ss release];
	[ignoreList reloadData];

	int row = [[ssModel ignoreList] count] - 1;
	[ignoreList selectRow: row  byExtendingSelection: NO];

	[ignoreList 
		editColumn: 0  
		row: row
		withEvent: nil 
		select:YES];
}

//--------------------------------------------------------------------------------------------------
- (IBAction)removeIgnore:(id)sender
{
	NSIndexSet *selItems = [ignoreList selectedRowIndexes];
	if ([selItems count] != 1)
	{
		return;
	}

	int row = [selItems firstIndex];
	[[ssModel ignoreList] removeObjectAtIndex: row];
	[ignoreList reloadData];

	// Try to ensure something is selected
	if (-1 == [ignoreList selectedRow] && [[ssModel ignoreList] count] > 0)
	{
		while (row >= [[ssModel ignoreList] count] && row > 0)
		{
			--row;
		}
		[ignoreList selectRow: row  byExtendingSelection: NO];
	}
}

//--------------------------------------------------------------------------------------------------
- (IBAction)editIgnore:(id)sender
{
}

//--------------------------------------------------------------------------------------------------
- (IBAction)onCancel:(id)sender
{
	[self saveDialogData];
	[NSApp stopModalWithCode: 0];
	[mainWindow close];
}

//--------------------------------------------------------------------------------------------------
- (IBAction)onOK:(id)sender
{
	[ssModel setName: [nameText stringValue]];
	[ssModel setDuration: [durationTime intValue]];
	[ssModel setAutoShow: [autoSlides intValue]];
	[ssModel setSortBy: [order intValue]];

	// Save the slideshow; if there isn't a name, prompt the user for a folder & name.
	NSString *filename = [ssModel filename];
	if (nil == filename)
	{
		NSSavePanel *save = [NSSavePanel savePanel];
		[save setCanCreateDirectories: YES];
		if (NSOKButton == [save runModalForDirectory: GetPicturesFolder()  file:@""])
		{
			filename = [save filename];
		}
	}

	if (YES != [ssModel saveToFile: filename])
	{
NSLog(@"failed saving to %@", filename);
		return;
	}

	[self saveDialogData];
	[NSApp stopModalWithCode: 1];
	[mainWindow close];
}

//--------------------------------------------------------------------------------------------------
- (id)tableView
		: (NSTableView *)table
		objectValueForTableColumn: (NSTableColumn *)column
		row: (int)row;
{
	SSPathData *ssData = nil;
	if (table == folderList)
	{
		ssData = [[ssModel folderList] objectAtIndex: row];
	}
	else
	{
		ssData = [[ssModel ignoreList] objectAtIndex: row];
	}

	if ([[column identifier] isEqual: @"name"])
	{
		return [ssData name];
	}
	else
	if ([[column identifier] isEqual: @"recursive"])
	{
		return [NSNumber numberWithBool: [ssData includeSubFolders]];
	}
	else
	if ([[column identifier] isEqual: @"enabled"])
	{
		return [NSNumber numberWithBool: [ssData enabled]];
	}

	return nil;
}

//--------------------------------------------------------------------------------------------------
- (void) tableView
	:(NSTableView *)table 
	setObjectValue:obj 
	forTableColumn:(NSTableColumn *)column 
	row:(int)row
{
	SSPathData *ssData = nil;
	if (table == folderList)
	{
		ssData = [[ssModel folderList] objectAtIndex: row];
	}
	else
	{
		ssData = [[ssModel ignoreList] objectAtIndex: row];
	}

	if ([[column identifier] isEqual: @"name"])
	{
		[ssData setName: obj];
	}
	else
	if ([[column identifier] isEqual: @"recursive"])
	{
		[ssData setIncludeSubFolders: [obj boolValue]];
	}
	else
	if ([[column identifier] isEqual: @"enabled"])
	{
		[ssData setEnabled: [obj boolValue]];
	}
}

//--------------------------------------------------------------------------------------------------
- (int) numberOfRowsInTableView:(NSTableView *)table
{
	if (table == folderList)
	{
		return [[ssModel folderList] count];
	}
	else
	{
		return [[ssModel ignoreList] count];
	}
}

//--------------------------------------------------------------------------------------------------
- (void) tableViewSelectionDidChange: (NSNotification *)note
{
//	[self updateUIFromSelection];
}

//--------------------------------------------------------------------------------------------------
- (NSWindow *) mainWindow
{
	return mainWindow;
}

//--------------------------------------------------------------------------------------------------
- (void) saveDialogData
{
	NSUserDefaults *userPrefs = [[Controller sharedController] userPreferences];
	NSRect frame = [[self mainWindow] frame];
	[userPrefs setObject: NSStringFromRect(frame)  forKey: PREF_EDIT_SLIDESHOW_FRAME_RECT];
}

@end
